//
//  DeviceWebView.m
//  Shion
//
//  Created by Chris Karr on 12/18/07.
//  Copyright 2007-2008 Audacious Software. All rights reserved.
//

#import "DeviceWebView.h"
#import "Device.h"
#import "DevicesModel.h"

@implementation DeviceWebView

- (void) awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInfo:) name:DEVICES_UPDATED object:nil];
}

- (void) updateInfo: (NSNotification *) msg
{
	if ([[msg object] boolValue])
		[self updateDeviceInfo];
}

- (void) updateDeviceInfo
{
	WebFrame * mainFrame = [self mainFrame];
	
	if ([[devices selectedObjects] count] > 0)
	{
		Device * d = [[devices selectedObjects] objectAtIndex:0];

		NSMutableString * htmlString = [NSMutableString stringWithContentsOfFile:
											[[NSBundle mainBundle] pathForResource:@"device" ofType:@"html"]];
											
		[htmlString replaceOccurrencesOfString:@"%DEVICE_NAME%" withString:d.name options:NSCaseInsensitiveSearch 
			range:NSMakeRange (0, [htmlString length])];

		[htmlString replaceOccurrencesOfString:@"%DEVICE_ADDRESS%" withString:[d addressString] options:NSCaseInsensitiveSearch 
			range:NSMakeRange (0, [htmlString length])];

		if (!d.dimmer)
		{
			if ([d.actualStatus.lightLevel integerValue] != 0)
			{
				[htmlString replaceOccurrencesOfString:@"%DEVICE_STATUS%" withString:@"on" options:NSCaseInsensitiveSearch 
					range:NSMakeRange (0, [htmlString length])];
			}
			else
			{
				[htmlString replaceOccurrencesOfString:@"%DEVICE_STATUS%" withString:@"off" options:NSCaseInsensitiveSearch 
					range:NSMakeRange (0, [htmlString length])];
			}
		}
		else
		{
			[htmlString replaceOccurrencesOfString:@"%DEVICE_STATUS%" withString:
					[NSString stringWithFormat:@"%d", (([d.actualStatus.lightLevel integerValue] + 1) / 32)] options:NSCaseInsensitiveSearch 
					range:NSMakeRange (0, [htmlString length])];
		}
		
		[mainFrame loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]]; 
	}
}

@end
